<template>
  <div id="main">
      <div class="container" v-if="current_user">
          <h2 style="float:left;">{{ current_user.get('username') }}</h2>
          <button type="button" class="btn" style="margin:17px 5px 0 20px;" v-if="user.id != current_user.id" @click="toggleFollow">{{ followed? '取消关注':'＋ 关注' }}</button>
          <hr style="clear:both;">
          <div class="oprator" v-if="user">
              <!--<button type="button" class="btn" v-if="user.id != current_user.id" @click="toggleFollow">{{ followed? '取消关注':'＋关注' }}</button>-->
             <p>此处留言：</p>
              <mt-field type="textarea" row="5" id="msg" v-model="msg"></mt-field>
              <button type="button" class="btn" v-if="user.id != current_user.id" @click="sendMsg">发送留言</button>
          </div>
          <hr>
          <div class="oprator" v-if="user">
              <p>对话消息：</p>
              <mt-field  type="textarea" row="5" id="talk" v-model="talk"></mt-field>
              <button type="button" class="btn" v-if="user.id != current_user.id" @click="sendTalk">发送消息</button>
          </div>
          <h1>{{resp}}</h1>
      </div>
  </div>
</template>
<script>
    import { mapState } from 'vuex';
    import { Toast } from 'mint-ui';
    var TextMessage = require('leancloud-realtime').TextMessage;

    export default {
        name: 'user',
        data () {
            const id = this.$route.params.id;
            return {
                current_user: null,
                followed: false,
                id,
                dialogFormVisible: false,
                msg: '',
                resp:'',
                req:'',
                talk:''
            };
        },
        computed: mapState(['user']),
        created(){
            this.getCurrentUser();
        },
        methods: {
            getCurrentUser(){
                const id = this.id;
                let q = new this.$api.SDK.Query('_User');
                q.get(id).then((user) => {
                    this.current_user = user;
                    return user;
                }).then((user) => {
                    this.checkFollowed();
                }).catch(console.error);
            },
            toggleFollow(){
                const id = this.id;
                if(this.followed){
                    // 取消关注
                    this.user.unfollow(id).then(() => {
                        this.followed = false;
                        Toast({
                            message:'取消关注成功',
                            iconClass:'icon icon-success'
                        })
                    }).catch(console.error);
                }else{
                    // 关注
                    this.user.follow(id).then(() => {
                        this.followed = true;
                        Toast({
                            message:'关注成功',
                            iconClass:'icon icon-success'
                        })
                    }).catch(console.error);
                }
            },
            checkFollowed(){
                const id = this.id;
                const q = this.user.followeeQuery();
                q.include('followee');
                q.find().then(followee => {
                    if (followee.length) {
                        if (followee.some(f => f.id == id)) {
                            this.followed = true;
                        }
                        return;
                    }
                }).catch(console.error)
            },
            sendMsg(){
                if (!this.msg) {
                    Toast({
                        message:'信息不能为空',
                        iconClass:'icon icon-success'
                    })
                    return;
                }

                const Status = this.$api.SDK.Status;
                const status = new Status(null, this.msg);
                status.set('from', this.user);
                status.set('to', this.current_user);
                Status.sendPrivateStatus(status, this.current_user.id).then((status) => {
                    if (status) {
                        Toast({
                            message:'发送私信成功',
                            iconClass:'icon icon-success'
                        })
                    }
                },(err) =>{
                    this.$message.error(err);
                })
            },
            sendTalk(){
                if (!this.talk) {
                    Toast({
                        message:'信息不能为空',
                        iconClass:'icon icon-success'
                    })
                    return;
                }
                const id = this.$route.params.id;
                const that = this
                const toId = this.user.id
                this.$api.realtime.createIMClient(toId).then(function(tom) {
                    return tom.createConversation({
                        members: [id],
                        name: 'To/m & Jerry',
                    });
                }).then(function(conversation) {
                    // 发送消息
                    return conversation.send(new TextMessage(that.talk));
                }).then(function(message) {
                    console.log('Tom & Jerry', '发送成功！');
                }).catch(console.error);
            }
        },
        mounted(){
            var that = this
            const toId = this.user.id
            console.log(toId);
            this.$api.realtime.createIMClient(toId).then(function(jerry) {
                jerry.on('message', function(message, conversation) {
                    let q = new that.$api.SDK.Query('_User');
                    q.get(message.from).then((user) => {
                        Toast({
                            message: '您收到了一个来自'+ user.attributes.username +'的消息: ' + message.text,
                            iconClass:'icon icon-success'
                        })
                    })
                });
            }).catch(console.error);
        }
    };
</script>

<style lang="css" scoped>
    .btn {
        border-radius: 5px;
        background: #41b883;
        color: white;
        margin-top: 10px;
    }

    .oprator {
        width: 100%;
    }

    .oprator p{
        font-size: 16px;
    }

    .oprator #msg, .oprator #talk{
        width: 100%;
        height: 80px;
        line-height: 20px;
        font-size: 16px;
        padding: 0;
        resize: none;
        border: 1px solid #ccc;
    }
</style>